package fun.tan90.easy.binlog.manager.utils;

import cn.hutool.core.util.StrUtil;
import fun.tan90.easy.binlog.base.convention.enums.IErrorCode;
import fun.tan90.easy.binlog.base.convention.exception.ClientException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/9/8 21:21
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DataSourceUtil {

    /**
     * 检查数据连接信息是否正确
     * 检查主库是否开启binlog
     *
     * @param hostname
     * @param port
     * @param username
     * @param password
     * @return
     */
    public static String checkMaster(String hostname, Integer port, String username, String password) {
        String url = StrUtil.format("jdbc:mysql://{}:{}", hostname, port);
        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            try (Connection connection = DriverManager.getConnection(url, username, password);
                 Statement statement = connection.createStatement()) {
                ResultSet resultSet = statement.executeQuery("SHOW VARIABLES LIKE 'log_bin'");
                String value = "off";
                while (resultSet.next()) {
                    value = resultSet.getString("Value");
                }
                log.info("MySQL【{}】连接成功, binlog {}", url, value);
                if ("off".equalsIgnoreCase(value)) {
                    throw new ClientException(IErrorCode.BINLOG_1004010, "主库尚未开启binlog");
                }
            }
        } catch (Exception e) {
            throw new ClientException(IErrorCode.BINLOG_1004010, e.getMessage());
        }
        return "success";
    }
}